#include "RecordVideoThread.h"

// Qt includes
#include <QtCore/QFile>

// Local includes
#include "Video.h"
#include "IpcClient.h"

static const int QueueLimit = 5;

RecordVideoThread::RecordVideoThread(Video *video, IpcClient *client, QObject *parent)
 : QThread(parent), mOutputFile(0), mVideo(video), mIpcClient(client)
{
	connect(mIpcClient, SIGNAL(serverAcknowledged()), this, SLOT(onNewFrame()));
}

void RecordVideoThread::run()
{
	exec();
}

void RecordVideoThread::setOutputFileName(const QString &fileName)
{
	mOutputFile = new QFile(fileName);
}

void RecordVideoThread::flushQueueToDisk()
{
	mOutputFile->open( QFile::WriteOnly | QFile::Append );

	while( !mFrameQueue.empty() )
	{
		mOutputFile->write( mFrameQueue.dequeue() );
	}

	mOutputFile->close();
}

void RecordVideoThread::onNewFrame()
{
	mFrameQueue.enqueue( QByteArray(reinterpret_cast<const char*>(mVideo->data()), (int)mVideo->dataSize()) );

	if( mFrameQueue.size() > QueueLimit )
	{
		flushQueueToDisk();
	}
}
